package org.example.springbootblog.common.pojo.utils;

import org.example.springbootblog.common.exception.BlogException;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class SecurityUtil {

    //加密
    public static String encrypt(String password) {
        if (!StringUtils.hasLength(password)) {
            throw new BlogException("密码不能为空");
        }

        //生成盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //对盐值和明文密码加密  md5  得到64位16进制的密文
        String securityPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        return salt+ securityPassword;  //数据库中存储 盐值 + 密文
    }

    //验证

    public static boolean verify(String inputPassword, String sqlPassword) {
        //参数检验
        if (!StringUtils.hasLength(inputPassword) || !StringUtils.hasLength(sqlPassword)) {
            return false;
        }

        if (sqlPassword.length() != 64) {
            return false;
        }

        //获取盐值  salt
        String salt = sqlPassword.substring(0,32);
        //加密
        String securityPassword = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes(StandardCharsets.UTF_8));
        //看看和数据库中的是否相同
        return sqlPassword.equals(salt + securityPassword);
    }
}
